﻿using System.Configuration;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private const string CustomConfigFileName = "CustomApp.config";

    public MainWindow()
    {
        InitializeComponent();
        ReadFilePathsFromConfig();
    }

    private void ReadFilePathsFromConfig()
    {
        try
        {
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = CustomConfigFileName };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            var configItems = new Dictionary<string, string>();
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                configItems[key] = config.AppSettings.Settings[key].Value;
            }

            // 这里可以将读取到的配置项用于后续操作
            foreach (var item in configItems)
            {
                MessageBox.Show($"键: {item.Key}, 值: {item.Value}");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"读取配置文件时出错: {ex.Message}");
        }
    }

    private void WriteFilePathsToConfig(Dictionary<string, string> configItems)
    {
        try
        {
            var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = CustomConfigFileName };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            config.AppSettings.Settings.Clear();

            foreach (var item in configItems)
            {
                config.AppSettings.Settings.Add(item.Key, item.Value);
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
            MessageBox.Show("配置项已成功写入配置文件。");
        }
        catch (Exception ex)
        {
            MessageBox.Show($"写入配置文件时出错: {ex.Message}");
        }
    }

    private void TestWriteButton_Click(object sender, RoutedEventArgs e)
    {
        var testConfigItems = new Dictionary<string, string>
            {
                { "FilePath1", @"C:\TestFiles\file1.txt" },
                { "FilePath2", @"C:\TestFiles\file2.txt" },
                { "OtherSetting", "SomeValue" }
            };
        WriteFilePathsToConfig(testConfigItems);
    }
}